package com.chu.cloud.api.service;

import com.chu.cloud.dto.CouponsDto;
import com.chu.cloud.feign.client.ICouponFeignClient;
import com.chu.cloud.response.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.hateoas.PagedResources;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: Tianshu.CHU
 * @Date: 2018/5/3 20:20
 * @Description:
 */
@Service
public class ShopCouponService {

    @Autowired
    private ICouponFeignClient couponFeignClient;

    @Autowired
    private RestTemplate restTemplate;


    public Integer userGetCoupon(Integer couponId, Integer userId) {
        ResponseMessage<Integer> result = couponFeignClient.userGetCoupon(userId, couponId);
        if (result.getCode() != 200){
            return -1;
        }
        return result.getData();
    }

    public List<CouponsDto> enableReceiveCoupons(Integer shopId){
        String url = "http://chu-marketing-microservice/discountCoupons/search/" +
                "enableReceive?shopId=%s&status=%s";
        url = String.format(url, shopId, 2);
        ParameterizedTypeReference<PagedResources<CouponsDto>> responseType =
                new ParameterizedTypeReference<PagedResources<CouponsDto>>() {
                };
        PagedResources<CouponsDto> response = restTemplate.exchange(url, HttpMethod.GET, null, responseType).getBody();
        Collection<CouponsDto> result = response.getContent();
        List<CouponsDto> couponsDtos = result.stream().filter(c -> c.getStartTime().compareTo(new Date()) <= 0).collect(Collectors.toList());
        return couponsDtos;
    }

}
